import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect,Link} from 'mirrorx';
import { createForm } from 'rc-form';
import { List, InputItem, WhiteSpace, WingBlank, Button,Checkbox,Picker,Flex,Tabs,Modal,Icon, Radio } from 'antd-mobile';

const RadioItem = Radio.RadioItem;

class App extends React.Component { 
	constructor(props) {
		super(props);
        this.state={
            healthPolicy:[],
            errorMap:[],
            over:false,
            allAnswers:[],
            groupType:"HOLDERINFORM"
        }
        this.answerArr = [];
	}

	componentDidMount(){
        this.requestHealthPolicy("HOLDERINFORM"); //先请求投保人告知		
    }

    requestHealthPolicy=(groupType)=>{
        //告知有两种 分别请求一次
        // HOLDERINFORM
        // INSURANTINFORM	
        if(groupType == "INSURANTINFORM"){
            this.setState({
                over:true
            })
        }
        T.fetch({
            url:"/market/health/inform.json",
            loading:true,
            data:{packageId:T.urlQuery("packageId"),groupType:groupType}
        }).then((res)=>{
            if(res.success){                   
                if(res.value){
                            const media = res.value.packageInformResponseDTOList;
                            var m = 0,
                              n = 0,
                              t = 0;  
                            for (m = 0; m < media.length; m++) {  
                                for (n = 0; n < media.length; n++) {  
                                    if (media[m].informCategoryOrderNo <= media[n].informCategoryOrderNo) {                                          
                                        t = media[m];  
                                        media[m] = media[n];  
                                        media[n] = t;  
                                    }  
                                }  
                            } 
                    res.value.packageInformResponseDTOList = media;        
                    this.setState({
                    healthPolicy:res.value,
                    groupType:groupType 
                    })
                } else{ //沒有投保人告知則請求被保人告知
                    this.requestHealthPolicy("INSURANTINFORM");
                }           
                
            }
        })       
    }

    clickNext=()=>{
        if(this.state.over == false){
            this.submit("HOLDERINFORM");
            this.requestHealthPolicy("INSURANTINFORM"); //再请求被保人告知
        }else{
            this.submit("INSURANTINFORM");
        }         
    }
    
    onChange=(Qid,Aid,answer)=>{ 
        let healthPolicy = this.state.healthPolicy;
        let dtos = healthPolicy.packageInformResponseDTOList;
          for (var i = 0; i<dtos.length;i++){              
            for (var n = 0; n<dtos[i].informQuestionList.length;n++){               
                if(Qid == dtos[i].informQuestionList[n].id){  //问题id
                    for(var j = 0; j < dtos[i].informQuestionList[n].informQuestionAnswerList.length; j++){  //单选答案数组                     
                        dtos[i].informQuestionList[n].informQuestionAnswerList[j].isCheck = false;
                        if(Aid ==  dtos[i].informQuestionList[n].informQuestionAnswerList[j].id){ //答案id
                            dtos[i].informQuestionList[n].informQuestionAnswerList[j].isCheck = true;
                        }
                     }                
                }
            }            
        }
        healthPolicy.packageInformResponseDTOList = dtos;
        this.setState({
            healthPolicy:healthPolicy
        })             
    }
    dealAnswer=()=>{ //处理答案
        const healthPolicy = this.state.healthPolicy;
        const dtos = healthPolicy.packageInformResponseDTOList;
        let tips = []; //答案数组
        let obj = {}; //答案对象
         for (var i = 0; i<dtos.length;i++){             
            for (var n = 0; n<dtos[i].informQuestionList.length;n++){ 
                if(dtos[i].informQuestionList[n].answerType == "RADIO"){
                    obj = {questionId: dtos[i].informQuestionList[n].id , values:[]}   //问题id             
                        for(var j = 0; j < dtos[i].informQuestionList[n].informQuestionAnswerList.length; j++){  //单选答案数组  
                            if(dtos[i].informQuestionList[n].informQuestionAnswerList[j].isCheck){
                                if(dtos[i].informQuestionList[n].informQuestionAnswerList[j].isCheck == true){
                                    obj.values.push({answerId:dtos[i].informQuestionList[n].informQuestionAnswerList[j].id,value:''})
                                }
                            }                   
                            
                        }                
                    tips.push(obj);
                }                
            }
        }
       return tips;
    }
    onErrorClick=(question)=>{	//点击报错icon出现的提示	        
		const {getFieldError } = this.props.form;
		let msg = getFieldError(question);
		if(msg){			
			T.showError(msg.join(","));
		}	
	}  

   submit=(informGroupType)=>{ 
       let tipsResult = {};
       let tips = this.dealAnswer(); 
       let allAnswers = this.state.allAnswers;     
       this.props.form.validateFields((error, values) => {
            var errorMap ={}
			if(error){
				for(var key in error){
					errorMap[key] = 1;
				}
			}else{
				//没有错误                               			
                for (var key in values){                 
                  tips.push({questionId:key,values:[{value:values[key]}]});
                 }  
                 tipsResult = {"informGroupType":informGroupType,tips}; 
                 this.setState({ allAnswers: allAnswers.push(tipsResult) });  //投保人告知和被保人告知的答案
                 sessionStorage.setItem("tipsResult",  JSON.stringify(allAnswers)); //答案放缓存
                 if(this.state.over == true)
                 actions.routing.push({pathname:'insure2',search:"?goodId="+T.urlQuery("goodId")+"&packageId="+T.urlQuery("packageId")+"&planId="+T.urlQuery("planId")});              
			}
            this.setState({
				errorMap
			});
        })        
   }
    
	
	
	render() {
        const healthPolicy = this.state.healthPolicy;
        const { getFieldProps } = this.props.form;    

		return (<div className="health-policy">       
		<div className="health">
        <p className="f30 strong">{this.state.groupType == "HOLDERINFORM" ? "HOLDER INFORM" : "INSURANT INFORM"}</p>
        {
            healthPolicy.packageInformResponseDTOList && healthPolicy.packageInformResponseDTOList.map((item,index)=>
            <div key={index} className="itemWrap">
                <p className="title">{item.informCategoryName}</p>
                <List>
                    {item.informQuestionList && item.informQuestionList.map((infoQ,index)=> 
                        <div key={index}>                   
                         {infoQ.answerType == "QA" &&
                            <InputItem  key={index}
                            {...getFieldProps(infoQ.id+'',{
                               rules: [{
                                    required: "required",
                                    message:"请输入"+ infoQ.question,						
						        }]
                            })}
                            type="text"				
                            error ={this.state.errorMap[infoQ.id]}
                            onErrorClick={this.onErrorClick.bind(this,infoQ.id)}
                            clear
                            placeholder={"请输入"}
                            labelNumber={12}
                            >{infoQ.question}</InputItem>	
                        }
                         {infoQ.answerType == "RADIO" && 
                         <div className="radioWrap">
                            <p className="ques">{infoQ.question}</p>  
                            <div className="radioBox">    
                            {infoQ.informQuestionAnswerList.map((QAdto,index)=>
                                <div key={index} className="radioInner">
                                <span className="rSpan" >{QAdto.answer}</span>                                
                                    <RadioItem  key={infoQ.question} defaultChecked={QAdto.isDefault=='YES'} checked={QAdto.isCheck} onChange={() => this.onChange(infoQ.id,QAdto.id,QAdto.answer)}>
                                    </RadioItem>
                                </div>                              
                            )}
                            </div>    
                         </div>                          
                        }
                       </div>
                     )} 
                </List> 
            </div>           
            )}
        
     </div>

     <div className="footer">
            {/*<table>
                <tbody>
                    <tr>
                        <td className="bor-right"  style={{width:"50%"}}>
                            <a href="javascript:;" className="f32  tac fcw diy_background">YES</a>
                        </td>
                        
                        <td style={{width:"50%"}}>
                            <a href="javascript:;"  className="f32 tac fcw diy_background" >NO</a>
                        </td> 
                    </tr>
                </tbody>
            </table>*/}
            <div  style={{width:"100%"}}>
                <a href="javascript:;" className="f32  tac fcw diy_background" onClick={this.clickNext}>NEXT</a>
             </div>
     </div>   
			
	  	</div>)
	}
}

const AppForm = createForm()(App);
export default AppForm;